<template>
  <div style="padding-top: 65px; background-color: #F0F2F5; padding-bottom: 10px;">
    <sunDrawerBack show="show_statistics" :parent="this.$parent.$parent" />
    <!-- ${currentItem.description} -->
    <el-page-header class="sun-el-page-header" :content="`${currentItem.title}-统计`" @back="goBack" />

    <!-- 积极消极比例统一图 -->
    <div style="position: relative; height: 50px;">
      <div style="width: calc(100% - 50px); margin-left: 25px; position: relative; margin-top: 15px;">
        <div :style="{ 'width': `${positive_ratio}%`, 'height': '35px', 'float': 'left', 'background-color': '#3581E5', 'text-align': 'center', 'line-height': '35px', 'color': '#FFFFFF' }">
          积极评论（{{ positive_ratio }}%）
        </div>
        <div :style="{ 'width': `${passive_ratio}%`, 'height': '35px', 'float': 'left', 'background-color': '#F25B6A', 'text-align': 'center', 'line-height': '35px', 'color': '#FFFFFF' }">
          消极评论（{{ passive_ratio }}%）
        </div>
      </div>
      <div style="position: absolute; width: calc(100% - 30px); top: -20px; margin-left: 15px;">
        <el-image style="height: 70px; float: left;" fit="scale-down" :src="require('../../../assets/zan.png')" />
        <el-image style="height: 70px; float: right;" fit="scale-down" :src="require('../../../assets/cai.png')" />
      </div>
    </div>
    <el-card v-loading="scatterDiagramLoading" class="sun-el-card">
      <!-- 散点图 -->
      <div id="scatter_diagram" style="width: 100%; height: 400px;" />
    </el-card>
    <el-card v-loading="otherLoading" class="sun-el-card">
      <el-row style="margin-bottom: 15px;">
        <el-button :type="btn1_type" @click="feelingData('positive')">积极评论</el-button>
        <el-button :type="btn2_type" @click="feelingData('passive')">消极评论</el-button>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <div id="word_cloud" style="width: 100%; height: 400px; box-shadow: rgba(0, 0, 0, 0.5) 1px 1px 30px -25px; border-radius: 10px;" />
        </el-col>
        <el-col :span="8">
          <div id="male_female_ratio" style="width: 100%; height: 400px; box-shadow: rgba(0, 0, 0, 0.5) 1px 1px 30px -25px; border-radius: 10px;" />
        </el-col>
        <el-col :span="8">
          <div id="map_scattergram" style="width: 100%; height: 400px; box-shadow: rgba(0, 0, 0, 0.5) 1px 1px 30px -25px; border-radius: 10px;" />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { get } from '@/api/request'
// import { $tooltips } from '@/sun-components/SunMsg.js'
import SunDrawerBack from '@/sun-components/SunDrawerBack'
import { loadBMap } from '@/assets/js/map.js'
import * as echarts from 'echarts'
// 引入词云组件 需要执行命令安装对应包 npm install --save echarts-wordcloud
import 'echarts-wordcloud'
import 'echarts/extension/bmap/bmap'

export default {
  name: 'Statistics',
  components: { SunDrawerBack },
  data() {
    return {
      // 积极消极比例
      ratioLoading: false,
      positive_ratio: '50',
      passive_ratio: '50',

      // 评论情绪分值散点图
      scatterDiagramLoading: false,
      otherLoading: false,

      btn1_type: 'primary',
      btn2_type: ''
    }
  },
  computed: {
    currentItem() {
      return this.$parent.$parent.currentItem
    },
    show_statistics() {
      return this.$parent.$parent.show_statistics
    }
  },
  watch: {
    show_statistics: {
      handler: function(show) {
        if (show) {
          this.requestRatio()
          this.requestScatterDiagram()
          this.requestWordCloud()
          this.requestMaleFemaleRatio()
          this.requestMapScattergram()
        }
      }
    }
  },
  created() {
    const _that = this
    if (_that.show_statistics) {
      console.log('打开了', this.currentItem)
    }
  },
  mounted() {
    loadBMap('flo2KhWaWn0Gnw96y4UiGVKOTqctMG0Y').then(() => {
      this.initEchart()
      // const scatterDiagram = echarts.init(document.getElementById('scatter_diagram'))
      // // 设置图表选项
      // const option = {}
      // scatterDiagram.setOption(option)
      // this.initEchart()
      this.requestRatio()
      this.requestScatterDiagram()
      this.requestWordCloud()
      this.requestMaleFemaleRatio()
      this.requestMapScattergram()
    })
  },
  destroyed() { // 销毁实例解决图标未初始化完成快速切换出现错误
    this.initEchart()
  },
  methods: {
    feelingData(feeling) {
      if (feeling === 'positive') {
        this.btn1_type = 'primary'
        this.btn2_type = ''
      } else {
        this.btn1_type = ''
        this.btn2_type = 'primary'
      }
      this.requestWordCloud(feeling)
      this.requestMaleFemaleRatio(feeling)
      this.requestMapScattergram(feeling)
    },
    upData() {
      this.initEchart()
      this.requestRatio()
      this.requestScatterDiagram()
      this.requestWordCloud()
      this.requestMaleFemaleRatio()
      this.requestMapScattergram()
    },
    initEchart() {
      if (document.getElementById('scatter_diagram')) echarts.init(document.getElementById('scatter_diagram')).dispose()
      if (document.getElementById('word_cloud')) echarts.init(document.getElementById('word_cloud')).dispose()
      if (document.getElementById('male_female_ratio')) echarts.init(document.getElementById('male_female_ratio')).dispose()
      if (document.getElementById('map_scattergram')) echarts.init(document.getElementById('map_scattergram')).dispose()
    },
    async goBack() {
      this.$parent.$parent.show_statistics = false
    },
    // 消极、积极比例
    async requestRatio() {
      this.ratioLoading = true
      await get(`comments/feeling/ratio?video_id=${this.$parent.$parent.currentItem.id}`, {}).then(response => {
        if (response.code === 0) {
          this.positive_ratio = response.data.positive_ratio
          this.passive_ratio = response.data.passive_ratio
        }
        this.ratioLoading = false
      })
    },
    // 评论情绪分值散点图
    async requestScatterDiagram() {
      this.scatterDiagramLoading = true

      await get(`comments/feeling/scatter-diagram?video_id=${this.$parent.$parent.currentItem.id}`, {}).then(response => {
        if (response.code === 0) {
          // console.log(response.data)
          // 统计图配置
          const option = {
            title: {
              text: '男女评论情绪分值散点图'
              // subtext: 'Data from: Heinz 2003'
            },
            grid: {
              left: '3%',
              right: '3%',
              bottom: '7%',
              containLabel: true
            },
            tooltip: {
              // trigger: 'axis',
              showDelay: 0,
              formatter: function(params) {
                if (params.value.length > 1) {
                  return (
                    params.seriesName +
                    ' :<br/>' +
                    params.value[0] + '：' +
                    params.value[1]
                  )
                } else {
                  return (
                    params.seriesName +
                    ' :<br/>' +
                    params.name +
                    ' : ' +
                    params.value
                  )
                }
              },
              axisPointer: {
                show: true,
                type: 'cross',
                lineStyle: {
                  type: 'dashed',
                  width: 1
                }
              }
            },
            toolbox: {
              feature: {
                dataZoom: {},
                brush: {
                  type: ['rect', 'polygon', 'clear']
                }
              }
            },
            brush: {},
            legend: {
              data: ['女', '男'],
              left: 'center',
              bottom: 5
            },
            xAxis: [
              {
                type: 'value',
                scale: true,
                axisLabel: {
                  formatter: '{value}'
                },
                splitLine: {
                  show: false
                }
              }
            ],
            yAxis: [
              {
                type: 'value',
                scale: true,
                axisLabel: {
                  formatter: '{value}'
                },
                splitLine: {
                  show: false
                }
              }
            ],
            series: [
              {
                name: '女',
                type: 'scatter',
                emphasis: {
                  focus: 'series'
                },
                // prettier-ignore
                // data: [[1,5],[2,3],[3,6]]
                data: response.data.female_comment,
                // markArea: {
                //   silent: true,
                //   itemStyle: {
                //     color: 'transparent',
                //     borderWidth: 1,
                //     borderType: 'dashed'
                //   },
                //   data: [
                //     [
                //       {
                //         name: 'Female Data Range',
                //         xAxis: 'min',
                //         yAxis: 'min'
                //       },
                //       {
                //         xAxis: 'max',
                //         yAxis: 'max'
                //       }
                //     ]
                //   ]
                // },
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                },
                markLine: {
                  lineStyle: {
                    type: 'solid'
                  },
                  // data: [{ type: 'average', name: 'AVG' }, { xAxis: 160 }]
                  data: [{ yAxis: response.data.score_line }]
                }
              },
              {
                name: '男',
                type: 'scatter',
                emphasis: {
                  focus: 'series'
                },
                // prettier-ignore
                // data: [[1,5],[2,3],[3,6]]
                data: response.data.male_comment,
                // markArea: {
                //   silent: true,
                //   itemStyle: {
                //     color: 'transparent',
                //     borderWidth: 1,
                //     borderType: 'dashed'
                //   },
                //   data: [
                //     [
                //       {
                //         name: 'Male Data Range',
                //         xAxis: 'min',
                //         yAxis: 'min'
                //       },
                //       {
                //         xAxis: 'max',
                //         yAxis: 'max'
                //       }
                //     ]
                //   ]
                // },
                markPoint: {
                  data: [
                    { type: 'max', name: 'Max' },
                    { type: 'min', name: 'Min' }
                  ]
                },
                markLine: {
                  lineStyle: {
                    type: 'solid'
                  },
                  // data: [{ type: 'average', name: 'Average' }, { xAxis: 170 }]
                  data: [{ yAxis: response.data.score_line }]
                }
              }
            ]
          }

          // 构建统计图
          this.buildEchart('scatter_diagram', option)
        }
        this.scatterDiagramLoading = false
      })
    },
    // 积极或消极评论词云图
    async requestWordCloud(feeling = 'positive') {
      await get(`comments/feeling/${feeling}/word-cloud?video_id=${this.$parent.$parent.currentItem.id}`, {}).then(response => {
        if (response.code === 0) {
          // console.log(response.data)
          // 统计图配置
          const option = {
            series: [{
              type: 'wordCloud',
              shape: 'circle',
              left: 'center',
              top: 'center',
              width: '80%',
              height: '80%',
              right: null,
              bottom: null,
              sizeRange: [12, 60],
              rotationRange: [-90, 90],
              rotationStep: 45,
              gridSize: 8,
              drawOutOfBound: false,
              textStyle: {
                fontFamily: 'sans-serif',
                fontWeight: 'bold',
                color: () => {
                  // 马卡龙色系
                  const colors = ['#f09ea6', '#f3c1c2', '#fOd95d', '#94d4d1', '#6dbbc5']
                  return colors[Math.floor(Math.random() * colors.length)]
                }
              },
              data: response.data
            }]
          }

          // 构建统计图
          this.buildEchart('word_cloud', option)
        }
      })
    },
    // 积极或消极男女比例饼图
    async requestMaleFemaleRatio(feeling = 'positive') {
      await get(`comments/feeling/${feeling}/male-female-ratio?video_id=${this.$parent.$parent.currentItem.id}`, {}).then(response => {
        if (response.code === 0) {
          // console.log(response.data)
          // 统计图配置
          const option = {
            tooltip: {
              trigger: 'item'
            },
            legend: {
              top: '5%',
              left: 'center'
            },
            series: [
              {
                name: 'Access From',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                  borderRadius: 10,
                  borderColor: '#fff',
                  borderWidth: 2
                },
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: 40,
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: response.data
              }
            ]
          }

          // 构建统计图
          this.buildEchart('male_female_ratio', option)
        }
      })
    },
    // 积极或消极评论地图分布
    async requestMapScattergram(feeling = 'positive') {
      this.otherLoading = true
      await get(`comments/feeling/${feeling}/map-scattergram?video_id=${this.$parent.$parent.currentItem.id}`, {}).then(response => {
        if (response.code === 0) {
          // console.log(response.data)
          var option
          const data = response.data.data
          const geoCoordMap = response.data.geo_coord_map
          const convertData = function(data) {
            var res = []
            for (var i = 0; i < data.length; i++) {
              var geoCoord = geoCoordMap[data[i].name]
              if (geoCoord) {
                res.push({
                  name: data[i].name,
                  value: geoCoord.concat(data[i].value)
                })
              }
            }
            return res
          }
          option = {
            title: {
              text: '评论用户地图分布',
              // subtext: 'data from PM25.in',
              // sublink: 'http://www.pm25.in',
              left: 'center'
            },
            tooltip: {
              trigger: 'item'
            },
            bmap: {
              center: [116.339303, 39.889916],
              zoom: 6,
              roam: true,
              mapStyle: {
                styleJson: [
                  {
                    featureType: 'water',
                    elementType: 'all',
                    stylers: {
                      color: '#d1d1d1'
                    }
                  },
                  {
                    featureType: 'land',
                    elementType: 'all',
                    stylers: {
                      color: '#f3f3f3'
                    }
                  },
                  {
                    featureType: 'railway',
                    elementType: 'all',
                    stylers: {
                      visibility: 'off'
                    }
                  },
                  {
                    featureType: 'highway',
                    elementType: 'all',
                    stylers: {
                      color: '#fdfdfd'
                    }
                  },
                  {
                    featureType: 'highway',
                    elementType: 'labels',
                    stylers: {
                      visibility: 'off'
                    }
                  },
                  {
                    featureType: 'arterial',
                    elementType: 'geometry',
                    stylers: {
                      color: '#fefefe'
                    }
                  },
                  {
                    featureType: 'arterial',
                    elementType: 'geometry.fill',
                    stylers: {
                      color: '#fefefe'
                    }
                  },
                  {
                    featureType: 'poi',
                    elementType: 'all',
                    stylers: {
                      visibility: 'off'
                    }
                  },
                  {
                    featureType: 'green',
                    elementType: 'all',
                    stylers: {
                      visibility: 'off'
                    }
                  },
                  {
                    featureType: 'subway',
                    elementType: 'all',
                    stylers: {
                      visibility: 'off'
                    }
                  },
                  {
                    featureType: 'manmade',
                    elementType: 'all',
                    stylers: {
                      color: '#d1d1d1'
                    }
                  },
                  {
                    featureType: 'local',
                    elementType: 'all',
                    stylers: {
                      color: '#d1d1d1'
                    }
                  },
                  {
                    featureType: 'arterial',
                    elementType: 'labels',
                    stylers: {
                      visibility: 'off'
                    }
                  },
                  {
                    featureType: 'boundary',
                    elementType: 'all',
                    stylers: {
                      color: '#fefefe'
                    }
                  },
                  {
                    featureType: 'building',
                    elementType: 'all',
                    stylers: {
                      color: '#d1d1d1'
                    }
                  },
                  {
                    featureType: 'label',
                    elementType: 'labels.text.fill',
                    stylers: {
                      color: '#999999'
                    }
                  }
                ]
              }
            },
            series: [
              {
                name: '评论分数',
                type: 'scatter',
                coordinateSystem: 'bmap',
                data: convertData(data),
                symbolSize: function(val) {
                  return val[2]
                },
                encode: {
                  value: 2
                },
                label: {
                  formatter: '{b}',
                  position: 'right',
                  show: false
                },
                emphasis: {
                  label: {
                    show: true
                  }
                }
              },
              {
                name: 'Top 5',
                type: 'effectScatter',
                coordinateSystem: 'bmap',
                data: convertData(
                  data
                    .sort(function(a, b) {
                      return b.value - a.value
                    })
                    .slice(0, 6)
                ),
                symbolSize: function(val) {
                  return val[2]
                },
                encode: {
                  value: 2
                },
                showEffectOn: 'render',
                rippleEffect: {
                  brushType: 'stroke'
                },
                label: {
                  formatter: '{b}',
                  position: 'right',
                  show: true
                },
                itemStyle: {
                  shadowBlur: 10,
                  shadowColor: '#333'
                },
                emphasis: {
                  scale: true
                },
                zlevel: 1
              }
            ]
          }

          // 构建统计图
          this.buildEchart('map_scattergram', option)
        }

        this.otherLoading = false
      })
    },
    // 设置数据统计图【教秘、管理端】
    async buildEchart(document_id, option) {
      if (!echarts) {
        console.log('缺少echarts')
        return
      }
      var myChart = echarts.init(document.getElementById(document_id))
      console.log('myChart', myChart)
      myChart.setOption(option)
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/sun-style.scss';

.sun-form-pages ::v-deep {
  .el-switch__label {
    width: 35px !important;
    text-align: center !important;
  }
}
</style>
